package com.ruoyi.system.service;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.TicketBusiness;
import com.ruoyi.system.domain.TicketCustomer;
import com.ruoyi.system.domain.TicketTrans;
import com.ruoyi.system.domain.vo.StatisticsDateVo;
import com.ruoyi.system.domain.vo.StatisticsResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.validation.constraints.Size;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


@Service
public class TicketCommonService {

    @Autowired
    private ITicketTransService ticketTransService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ITicketBusinessService businessService;

    @Autowired
    private ITicketCustomerService customerService;

    /**
     * 获取当前登录人下面所有商户信息
     * @return
     */
    public List<TicketBusiness> getAllBusinessByCurrentUser()
    {
        List<TicketBusiness> businessNos = new ArrayList<>();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //当前登录人所在部门
        Long deptId = loginUser.getDeptId();
        //去部门表中拿到当前部门及其子部门
        List<SysDept> sysDepts = sysDeptService.currentDeptAndSub(deptId);
        List<Long> deptIds = sysDepts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
        for (Long id : deptIds) {
            //去用户表中拿到所有部门下用户
            List<SysUser> sysUsers = userService.selectUserByDeptId(id);
            for (SysUser sysUser : sysUsers) {
                @Size(min = 0, max = 30, message = "用户昵称长度不能超过30个字符") String name = sysUser.getNickName();
                if(!StringUtils.isEmpty(name)){
                    TicketBusiness business = businessService.selectTicketBusinessByBusinessName(name);
                    if(Objects.isNull(business)) continue;
                    businessNos.add(business);
                }
            }
        }
        return businessNos;
    }

    /**
     * 获取统计指标
     * @param dateVo
     * @return
     */
    public StatisticsResultVo getStatistics(StatisticsDateVo dateVo){
        StatisticsResultVo resultVo = new StatisticsResultVo();
        //统计当前登录账户下所有用户数量总和
        List<TicketCustomer> allCustomerByCurrentUser = getAllCustomerByCurrentUser();
        int size = allCustomerByCurrentUser.size();
        resultVo.setCustomerSum(BigDecimal.valueOf(size));
        //统计当前登录账户下所有交易金额总和
        List<TicketBusiness> allBusinessByCurrentUser = getAllBusinessByCurrentUser();
        List<String> businessNos = allBusinessByCurrentUser
                .stream()
                .map(TicketBusiness::getBusinessNo)
                .collect(Collectors.toList());
        //获取当前登录人下所有商户交易
        TicketTrans ticketTransVo = new TicketTrans();
        List<TicketTrans> trans = ticketTransService.selectTicketTransList(ticketTransVo);
        List<TicketTrans> currentAllTrans = trans.stream()
                .filter(p -> businessNos.contains(p.getTransBusinessNo()))
                .collect(Collectors.toList());
        BigDecimal transAmountSum = currentAllTrans
                .stream()
                .map(p -> BigDecimal.valueOf(Long.parseLong(p.getTransAmount())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        resultVo.setTransAmountSum(transAmountSum);
        //针对管理员统计日期筛选下所有交易金额前10的商户 。（维度：商户  、指标：商户金额总和)
        Map<String, List<TicketTrans>> businessTransDistribute = currentAllTrans.stream().collect(Collectors.groupingBy(TicketTrans::getTransCustomerNo));
        String year = dateVo.getYear(); //年
        String month = dateVo.getMonth(); //月
        String day = dateVo.getDay(); //日
        List<JSONObject> businessInfo = new ArrayList<>();
        Map<String,BigDecimal> businessDistribute = new HashMap<>();
        businessTransDistribute.forEach((k,v)->{
            //过滤年
            List<TicketTrans> yearTrans = v.stream().filter(p -> {
                Date transDate = p.getTransDate();
                Calendar instance = Calendar.getInstance();
                instance.setTime(transDate);
                if(StringUtils.isEmpty(year)) return true;
                return String.valueOf(instance.get(Calendar.YEAR)).equals(year);
            }).collect(Collectors.toList());
            //过滤月
            List<TicketTrans> monthTrans = yearTrans.stream().filter(p -> {
                Date transDate = p.getTransDate();
                Calendar instance = Calendar.getInstance();
                instance.setTime(transDate);
                if(StringUtils.isEmpty(month)) return true;
                return String.valueOf(instance.get(Calendar.MONTH)+1).equals(month);
            }).collect(Collectors.toList());
            //过滤天
            List<TicketTrans> dayTrans = monthTrans.stream().filter(p -> {
                Date transDate = p.getTransDate();
                Calendar instance = Calendar.getInstance();
                instance.setTime(transDate);
                if (StringUtils.isEmpty(day)) return true;
                return String.valueOf(instance.get(Calendar.DAY_OF_MONTH)).equals(day);
            }).collect(Collectors.toList());
            //统计该商户金额
            BigDecimal amount = dayTrans.stream().map(p -> BigDecimal.valueOf(Long.parseLong(p.getTransAmount())))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            TicketCustomer customer = customerService.selectTicketCustomerByCustomerNo(k);
            if(!Objects.isNull(customer)) {
                String customerName = customer.getCustomerName();
                if(StringUtils.isEmpty(customerName)){
                    customerName=k;
                }
                businessDistribute.put(customerName, amount);
            }
        });
        //分布排序且最多截取10户
        LinkedHashMap<String, BigDecimal> finalSortDistribute = businessDistribute.entrySet()
                .stream()
                .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
                .collect(Collectors.toMap(Map.Entry::getKey,
                        Map.Entry::getValue,
                        (e1, e2) -> e1, LinkedHashMap::new));
        AtomicInteger account = new AtomicInteger();
        finalSortDistribute.forEach((k,v)->{
            account.addAndGet(1);
            if(account.get()<10) {
                JSONObject temp = new JSONObject();
                temp.put("name",k);
                temp.put("value",v);
                businessInfo.add(temp);
            }
        });
        resultVo.setBusinessInfo(businessInfo);
        //针对管理员统计日期筛选下管理员账户下所有客户经理新增商户数量.（维度：客户经理、指标：当月新增商户数量总和)
        List<SysUser> userByRoleId = getUserByRoleId(101L);
        List<JSONObject> incrBusinessInfo = new ArrayList<>();
        Map<String,BigDecimal> incrBusinessDistribute = new HashMap<>();
        for (SysUser sysUser : userByRoleId) {
            SysDept dept = sysUser.getDept();
            Long deptId = dept.getDeptId();
            List<TicketBusiness> businessInfoByDeptId = getBusinessInfoByDeptId(deptId);
            //过滤年
            List<TicketBusiness> yearBusiness = businessInfoByDeptId.stream().filter(p -> {
                Date createTime = p.getCreateTime();
                Calendar instance = Calendar.getInstance();
                instance.setTime(createTime);
                if (StringUtils.isEmpty(year)) return true;
                return String.valueOf(instance.get(Calendar.YEAR)).equals(year);
            }).collect(Collectors.toList());
            List<TicketBusiness> monthBusiness = yearBusiness.stream().filter(p -> {
                Date transDate = p.getCreateTime();
                Calendar instance = Calendar.getInstance();
                instance.setTime(transDate);
                if (StringUtils.isEmpty(month)) return true;
                return String.valueOf(instance.get(Calendar.MONTH)+1).equals(month);
            }).collect(Collectors.toList());
            List<TicketBusiness> dayBusiness = monthBusiness.stream().filter(p -> {
                Date transDate = p.getCreateTime();
                Calendar instance = Calendar.getInstance();
                instance.setTime(transDate);
                if (StringUtils.isEmpty(day)) return true;
                return String.valueOf(instance.get(Calendar.DAY_OF_WEEK)).equals(day);
            }).collect(Collectors.toList());
            int businessSize = dayBusiness.size();
            incrBusinessDistribute.put(sysUser.getUserName(),BigDecimal.valueOf(businessSize));
        }
        //分布排序且最多截取10个客户经理
        LinkedHashMap<String, BigDecimal> finalSortIncrDistribute = incrBusinessDistribute.entrySet()
                .stream()
                .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
                .collect(Collectors.toMap(Map.Entry::getKey,
                        Map.Entry::getValue,
                        (e1, e2) -> e1, LinkedHashMap::new));
        AtomicInteger accountIncr = new AtomicInteger();
        finalSortIncrDistribute.forEach((k,v)->{
            accountIncr.addAndGet(1);
            if(accountIncr.get()<10) {
                JSONObject temp = new JSONObject();
                temp.put("name",k);
                temp.put("value",v);
                incrBusinessInfo.add(temp);
            }
        });
        resultVo.setIncrBusinessInfo(incrBusinessInfo);
        return resultVo;
    }

    /**
     * 获取当前登录人下面所有用户
     * @return
     */
    public List<TicketCustomer> getAllCustomerByCurrentUser(){
        List<TicketCustomer> customers = new ArrayList<>();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //当前登录人所在部门
        Long deptId = loginUser.getDeptId();
        //去部门表中拿到当前部门及其子部门
        List<SysDept> sysDepts = sysDeptService.currentDeptAndSub(deptId);
        List<Long> deptIds = sysDepts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
        for (Long id : deptIds) {
            //去用户表中拿到所有部门下用户
            List<SysUser> sysUsers = userService.selectUserByDeptId(id);
            for (SysUser sysUser : sysUsers) {
                @Size(min = 0, max = 30, message = "用户昵称长度不能超过30个字符") String name = sysUser.getNickName();
                if(!StringUtils.isEmpty(name)){
                    TicketCustomer ticketCustomer = customerService.selectTicketCustomerByCustomerName(name);
                    if(Objects.isNull(ticketCustomer)) continue;
                    customers.add(ticketCustomer);
                }
            }
        }
        return customers;
    }

    /**
     * 判断当前登陆人是否是商户
     * @return
     */
    public boolean isBusiness(){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //当前登录人所在部门
        Long deptId = loginUser.getDeptId();
        SysDept sysDept = sysDeptService.selectDeptById(deptId);
        String name = sysDept.getDeptName();
        TicketBusiness business = businessService.selectTicketBusinessByBusinessName(name);
        if(!Objects.isNull(business)){
            return true;
        }
        return false;
    }

    /**
     * 判断当前登陆人是否是客户
     * @return
     */
    public  boolean isCustomer(){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //当前登录人所在部门
        Long deptId = loginUser.getDeptId();
        SysDept sysDept = sysDeptService.selectDeptById(deptId);
        String name = sysDept.getDeptName();
        TicketCustomer ticketCustomer = customerService.selectTicketCustomerByCustomerName(name);
        if(!Objects.isNull(ticketCustomer)){
            return true;
        }
        return false;
    }

    //根据角色ID获取该角色下的用户
    public List<SysUser>  getUserByRoleId(Long roleId){
        return  userService.selectUserByRoleId(roleId);
    }

    public List<TicketBusiness> getBusinessInfoByDeptId(Long deptId){
        List<TicketBusiness> businessNos = new ArrayList<>();
        //去部门表中拿到当前部门及其子部门
        List<SysDept> sysDepts = sysDeptService.currentDeptAndSub(deptId);
        List<Long> deptIds = sysDepts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
        for (Long id : deptIds) {
            //去用户表中拿到所有部门下用户
            List<SysUser> sysUsers = userService.selectUserByDeptId(id);
            for (SysUser sysUser : sysUsers) {
                @Size(min = 0, max = 30, message = "用户昵称长度不能超过30个字符") String name = sysUser.getNickName();
                if(!StringUtils.isEmpty(name)){
                    TicketBusiness business = businessService.selectTicketBusinessByBusinessName(name);
                    if(Objects.isNull(business)) continue;
                    businessNos.add(business);
                }
            }
        }
        return businessNos;
    }


}
